package toolkits

import (
	"os/exec"
	"syscall"
	"time"
)

func WrapTimeout(cmd *exec.Cmd, timeout time.Duration) (err error, isTimeout bool) {
	done := make(chan error)
	go func() {
		done <- cmd.Wait()
	}()

	select {
	case <-time.After(timeout):
		go func() {
			<-done
		}()

		pid := cmd.Process.Pid
		{
			pss, _ := GetAllProcStatus()
			childPids := GetChildPids(pid, pss)
			for i := len(childPids) - 1; i > -1; i-- {
				childPid := childPids[i]
				syscall.Kill(childPid, syscall.SIGKILL)
			}
		}
		err = syscall.Kill(pid, syscall.SIGKILL)
		isTimeout = true
		return
	case err = <-done:
		isTimeout = false
		return
	}
}
